from django.shortcuts import render
from django.http import HttpResponse,JsonResponse
from django.views.decorators.csrf import csrf_exempt
from myadmin import models
from django.views.decorators.csrf import csrf_exempt
# Create your views here.
def index(request):

    vipuser = request.session.get('VipUser')
    # 判断当前用户是否登录
    if not vipuser['id']:
        return render(request,'myhome/login/login.html')

        # 获取用户对象
    obj = models.Users.objects.get(id=vipuser['id'])

    # 分配数据
    context = {'booktypes':gettypes(),'user':obj}
    return render(request,'myhome/cart/index.html',context)

def gettypes():
    # 获取首页的分类列表
    ts = models.booktype.objects.filter(pid=0)
    for x in ts:
        x.sub = models.booktype.objects.filter(pid=x.id)
    return ts

# 加入购物车
@csrf_exempt
def add(request):
    # 接收Ajax提交的数据
    data = request.POST.dict()
    vipuser = request.session.get('VipUser')
    # 判断当前用户是否登录
    if not vipuser['id']:
        return JsonResponse({'code':1,'msg':'当前用户没有登录'})
    # 准备数据，
    data['uid'] = models.Users.objects.get(id = vipuser['id'])
    data['bid'] = models.Books.objects.get(id = data['bid'])

    # 把数据添加的购物车
    try:
        # 判断当前加入购物车的商品是否已经存在
        cart = data['uid'].cart_set.filter(bid=data['bid'])
        if cart.count():
            obj = cart[0]
            obj.num += int(data['num'])
            obj.save()
        else:
            obj = models.Cart(**data)
            obj.save()
        return JsonResponse({'code':0,'msg':'加入购物车成功'})
    except:
        return JsonResponse({'code':1,'msg':'加入购物车失败'})

# 更新购物车
def edit(request):
    cartid = request.GET.get('cartid')
    num = request.GET.get('n')
    try:
        obj = models.Cart.objects.get(id=cartid)
        obj.num = num
        obj.save()
        return JsonResponse({'code':0,'msg':'更新购物车成功'})
    except:
        return JsonResponse({'code':1,'msg':'更新购物车失败'})

# 删除购物车
def delete(request):
    cartid = request.GET.get('cartid')
    try:
        obj = models.Cart.objects.get(id=cartid)
        obj.delete()
        return JsonResponse({'code':0,'msg':'商品删除成功'})
    except:
        return JsonResponse({'code':1,'msg':'商品删除失败'})